package com.example.erp.exception;

import com.example.erp.config.CommonConfig;
import com.example.erp.utils.Result;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 处理主键重复异常
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result handleDuplicateKeyException(DataIntegrityViolationException ex) {
        // 检查是否是主键重复异常
        if (ex.getCause() instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException sqlEx =
                    (SQLIntegrityConstraintViolationException) ex.getCause();
            // MySQL主键重复错误码
            if (sqlEx.getErrorCode() == 1062) {
                return Result.error(CommonConfig.errorMsg.SQLKEYERROR.getDescription());
            }
        }
        // 其他数据完整性异常
        return Result.error(CommonConfig.errorMsg.SQLERROR.getDescription());
    }

    // 1. 处理特定异常
    @ExceptionHandler(SQLException.class)
    public Result handleSQLException(SQLException ex) {
        return Result.error(CommonConfig.errorMsg.SQLERROR.getDescription());
    }

    // 兜底异常处理
    @ExceptionHandler(Exception.class)
    public Result error(Exception ex){
        String errorMsg = ex.getMessage() != null ? ex.getMessage() : CommonConfig.errorMsg.ERROR.getDescription(); // 获取异常消息
        ex.printStackTrace();
        return Result.error(errorMsg);
    }
}